#include "chathandler.h"
#include "clientsocket.h"

ChatHandler::ChatHandler(QObject *parent) : QObject(parent)
{
}

bool ChatHandler::handlePackage(Package *package)
{
    if( package->typ == TUNNEL_PACKAGETYP_MESSAGE )
    {
        handleNewMessage(package->from, package->message, package->to);

        return true;
    }
    else if( package->typ == TUNNEL_PACKAGETYP_SYSTEM )
    {
        handleSystemCommand(package->commandCategory, package->command, package->arguments);

        return true;
    }

    return false;
}

void ChatHandler::handleNewMessage(const QString &from, const QString &message, const QString &to)
{
    if( to.length() < 1 )
        emit newGlobalMessage(from, message);
    else
        emit newPrivateMessage(from, message, to);
}

void ChatHandler::handleSystemCommand(const quint16 &category, const quint16 &command, const QString &arguments)
{
    if( category == TUNNEL_COMMANDCATEGORY_COMM )
    {
        switch(command)
        {
        case TUNNEL_COMMAND_COMM_AUTH:
            emit authCommand(arguments);
            break;
        default:
            emit cError("Unknown Comm Command: "+command);
        }
    }
    else if( category == TUNNEL_COMMANDCATEGORY_FRIENDS )
    {
        switch(command)
        {
        case TUNNEL_COMMAND_FRIENDS_UPDATEFRIENDLIST:
            emit updateFriendlist(arguments);
            break;
        case TUNNEL_COMMAND_FRIENDS_GETFRIENDREQUESTS:
            emit incommingFriendrequest(arguments);
            break;
        case TUNNEL_COMMAND_FRIENDS_FRIENDGOESONLINE:
            emit signal_friendGoesOnline(arguments);
            break;
        case TUNNEL_COMMAND_FRIENDS_FRIENDGOESOFFLINE:
            emit signal_friendGoesOffline(arguments);
            break;
        default:
            emit cError("Unknown Friends Command: "+command);
        }
    }
    else if( category == TUNNEL_COMMANDCATEGORY_INFORMATION )
    {
        switch(command)
        {
        case TUNNEL_COMMAND_INFORMATION_ERRORMESSAGE:
            emit errorMessage(arguments);
            break;
        case TUNNEL_COMMAND_INFORMATION_INFOMESSAGE:
            emit infoMessage(arguments);
            break;
        default:
            emit cError("Unknown Error Command: "+command);
        }
    }
    else
        emit cError("Unknown System Command Categorie: "+category);
}
